﻿using System.Linq;
using System.Net.Mail;

namespace TaskKernel.Infrastructure
{
    public class SmtpSender : IMessageSender
    {
        private readonly MailMessage _mailMessage = new MailMessage();
        private readonly SmtpClient _smtpClient;

        public SmtpSender(string mailServer)
        {
            IsBodyHtml = true;
            _smtpClient = new SmtpClient(mailServer);
        }

        public bool IsBodyHtml { get; set; }

        #region IMessageSender Members

        public string MailServerAddress
        {
            get { return _smtpClient.Host; }
        }

        public bool SendMessage(TaskMessage taskMessage)
        {
            if (taskMessage.RecipientsAddress.GetList().Any()){
                if (taskMessage.Attachments.Any()){
                    foreach (var attachment in taskMessage.Attachments)
                        _mailMessage.Attachments.Add(attachment);
                }
                foreach (var address in taskMessage.RecipientsAddress.GetList())
                    _mailMessage.To.Add(new MailAddress(address));
                if (_mailMessage.To.Count > 0){
                    _mailMessage.From = new MailAddress(taskMessage.MessageSender, taskMessage.MessageSenderDisplayName);
                    _mailMessage.Subject = taskMessage.MessageSubject;
                    _mailMessage.Body = taskMessage.MessageBody;
                    _mailMessage.IsBodyHtml = IsBodyHtml;
                    _smtpClient.Send(_mailMessage);
                    return true;
                }
            }
            return false;
        }

        #endregion
    }
}